//
//  CAPersonalInformationVC.m
//  CleanerAir_Project
//
//  Created by 付亚杰 on 16/6/3.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "CAPersonalInformationVC.h"
#import "NSDate+Helper.h"
#import "NJImageCropperViewController.h"
#import "PersonalInformationModel.h"
#import "NSString+Check.h"

#define ORIGINAL_MAX_WIDTH 640.0f

@interface CAPersonalInformationVC ()<UITextFieldDelegate,UIImagePickerControllerDelegate ,NJImageCropperDelegate>{

    NSString *_sex;
    
    CGFloat _viewY;
    
}
//头像
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *changeHeadLabel;

//昵称
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UIImageView *removeNameImageView;

@property (weak, nonatomic) IBOutlet UIButton *genderBtn;

@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;

@property (weak, nonatomic) IBOutlet UITextField *mailTextField;
@property (weak, nonatomic) IBOutlet UIImageView *removeMailImageView;

@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UIImageView *removeAddressImageView;


@end

@implementation CAPersonalInformationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getInfoWithServer];
    
    self.nameTextField.delegate = self;
    self.mailTextField.delegate = self;
    self.addressTextField.delegate = self;
    
//    添加手势
    
    [self.removeNameImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeTextField:)]];
    [self.removeAddressImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeTextField:)]];
    [self.removeMailImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeTextField:)]];
    
    [self.headImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadImage)]];
    [self.changeHeadLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadImage)]];
    
    //选择 生日
    [self.birthdayLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dateClick)]];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

#pragma mark -- 重写父类
- (void)keyboardWillHide:(NSNotification *)aNotification
{
//    [super keyboardWillHide:aNotification];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.view.y = 64;
        
    }];
    
    NSLog(@"回收键盘-我是儿子");
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    
    [super keyboardWillShow:aNotification];
    
    NSLog(@"textView:%f,keyBoardH:%f",_viewY,self.keyBoardHeight);
    

    if (_viewY + self.keyBoardHeight + 64 > MAIN_HEIGHT) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.view.y = (MAIN_HEIGHT - _viewY - self.keyBoardHeight - 64) - 15;
            
        }];
    }
}


#pragma mark -- 选择性别
- (IBAction)selectSex:(id)sender {

    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择性别" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction *cameralAction = [UIAlertAction actionWithTitle:@"男" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

        _sex = @"1";
        [self.genderBtn setTitle:@"男" forState:(UIControlStateNormal)];
    }];
    
    UIAlertAction *photoAction =[UIAlertAction actionWithTitle:@"女" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

        _sex = @"2";
        [self.genderBtn setTitle:@"女" forState:(UIControlStateNormal)];
    }];
    
    UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"保密" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        _sex = @"0";
        [self.genderBtn setTitle:@"保密" forState:(UIControlStateNormal)];
    }];
    
    [alterController addAction:cancelAction];
    [alterController addAction:cameralAction];
    [alterController addAction:photoAction];
    
    
    [self presentViewController:alterController animated:YES completion:nil];
}

#pragma mark -- 获取个人信息
- (void)getInfoWithServer{
    
    [self showIndicator:@"正在加载个人信息，请稍候..."];
    
    __weak __typeof(self) weakSelf = self;
    
    NSString *urlStr = [NSString stringWithFormat:@"/Api/Member/info?login_token=%@&member_id=%@",[LoginSingleton sharedLoginSingleton].token,[LoginSingleton sharedLoginSingleton].loginModel.ids];
    
    [HTTPManager get:GET_URLString(urlStr) success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideIndicator];
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            PersonalInformationModel *model = [[PersonalInformationModel alloc] init];
            [model setValuesForKeysWithDictionary:responseObject[@"date"]];
            
            [LoginSingleton sharedLoginSingleton].perInfoModel = model;
            
            //显示
            [weakSelf accordingToView:model];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideIndicator];
    }];
}

//显示到View上
- (void)accordingToView:(PersonalInformationModel *)model{
    
//    NSLog(@"%@",Get_HeadImage_UrlString(model.avatar));
    if(model.avatar != nil){
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:Get_HeadImage_UrlString(model.avatar)] placeholderImage:[UIImage imageNamed:@"个人注册.png"]];
    }
    
    self.nameTextField.text = model.nickname;
    [self.genderBtn setTitle:model.sex forState:(UIControlStateNormal)];
    _sex = model.sexCode;
    
    
    self.birthdayLabel.text = [model.birthday isEqualToString:@""] || model.birthday == nil ? @"1990-01-01":model.birthday;
    self.mailTextField.text = [model.email isEqualToString:@""] || model.email == nil ? @"":model.email;
    self.addressTextField.text = [model.address isEqualToString:@""] || model.address == nil ? @"":model.address;
    
    
}

#pragma mark -- 选择生日
- (void)dateClick{
    
    [self.view endEditing:YES];
    
    UIDatePicker *picker = [[UIDatePicker alloc]init];
    picker.datePickerMode = UIDatePickerModeDate;
    
    picker.frame = CGRectMake(0, 40, MAIN_WIDTH, 200);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择\n\n\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSDate *date = picker.date;
        
        self.birthdayLabel.text = [date stringWithFormat:@"yyyy-MM-dd"];;
        
    }];
    [alertController.view addSubview:picker];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark -- 改变头像
- (void)changeHeadImage{
    
    __weak __typeof(self) weakSelf = self;
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择图片来源" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    UIAlertAction *cameralAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if ([weakSelf isCameraAvailable] && [weakSelf doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([weakSelf isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [weakSelf presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     //                                 NSLog(@"Picker View Controller is presented");
                                 }];
        }
        
    }];
    
    UIAlertAction *photoAction =[UIAlertAction actionWithTitle:@"从相册中选取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        // 从相册中选取
        if ([weakSelf isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [weakSelf presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     //                                 NSLog(@"Picker View Controller is presented");
                                 }];
        }
        
    }];
    
    [alterController addAction:cameralAction];
    [alterController addAction:photoAction];
    [alterController addAction:cancelAction];
    
    
    [self presentViewController:alterController animated:YES completion:nil];
    
}

#pragma mark -- 清楚文本
- (void)removeTextField:(UITapGestureRecognizer *)aTap{
    
    switch (aTap.view.tag) {
        case 10:{
            self.nameTextField.text = @"";
            break;
        }
        case 11:{
            self.mailTextField.text = @"";
            break;
        }
        case 12:{
            self.addressTextField.text = @"";
        }
        default:
            break;
    }
    
}

#pragma mark -- TextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    _viewY = [textField convertRect:textField.bounds toView:[[[UIApplication sharedApplication] delegate] window]].origin.y;
    
    switch (textField.tag) {
        case 10:{
            self.removeNameImageView.hidden = NO;
            break;
        }
        case 11:{
            self.removeMailImageView.hidden = NO;
            break;
        }
        case 12:{
            self.removeAddressImageView.hidden = NO;
        }
            
        default:
            break;
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    

    
    switch (textField.tag) {
        case 10:
            self.removeNameImageView.hidden = YES;
            break;
        case 11:
            self.removeMailImageView.hidden = YES;
            break;
        case 12:
            self.removeAddressImageView.hidden = YES;
            break;
        default:
            break;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark -- 保存
- (IBAction)submit:(id)sender {
    
    if ([self.nameTextField.text isEqualToString:@""]) {
        [ShowMessage showMessage:@"昵称不能为空"];
        return;
    }
    if([NSString isMail:self.mailTextField.text]){
        return;
    }
    
    [self changePerInfo];
    
}

#pragma mark -- 修改个人信息
- (void)changePerInfo{
    
    [self showIndicator:@"正在修改，请稍候..."];
    
    __weak __typeof(self) weakSelf  = self;
    
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:[LoginSingleton sharedLoginSingleton].loginModel.ids,@"member_id",[LoginSingleton sharedLoginSingleton].token,@"login_token",_sex,@"sex",self.nameTextField.text,@"nickname",self.birthdayLabel.text,@"birthday",self.addressTextField.text,@"address",self.mailTextField.text,@"email", nil];
    
    [HTTPManager post:GET_URLString(@"Api/Member/infoSub") parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"%@",responseObject[@"msg"]);
        
        [self hideIndicator];
        if ([responseObject[@"msg"] isEqualToString:@"修改成功"]) {
            
            [ShowMessage showCenterViewMessage:@"修改成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
            [ShowMessage showCenterViewMessage:@"修改失败"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",operation.responseObject);
        [self hideIndicator];
    }];
    
}

#pragma mark -- 选择头像

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(NJImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.headImageView.image = editedImage;
    });
    
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
#pragma mark - 上传头像
        
        [self uploadImage:editedImage];
    }];
}

- (void)imageCropperDidCancel:(NJImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - 上传头像
- (void)uploadImage:(UIImage *)image{
    
    [self showIndicator:@"正在上传头像，请稍候..."];
    
    NSData *data = UIImageJPEGRepresentation(image,0.75);
    
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:[LoginSingleton sharedLoginSingleton].loginModel.ids,@"id",[LoginSingleton sharedLoginSingleton].token,@"token",data,@"avatar",@"jpg",@"hz", nil];
    
//    NSDictionary *parameters = @{@"id":[LoginSingleton sharedLoginSingleton].loginModel.ids,@"token":[LoginSingleton sharedLoginSingleton].token,@"avatar":data};
    
    [HTTPManager post:GET_URLString(@"/Api/Member/editAvatar") parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [self hideIndicator];
        if([responseObject[@"msg"] isEqualToString:@"成功"]){
            
                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:responseObject[@"date"][@"path"] delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
            
                    [alert show];
            
            
            [ShowMessage showCenterViewMessage:@"上传成功"];
            
        }else{
            
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self hideIndicator];
        
    }];
}

#pragma mark - 修改头像
- (void)changeImageForWebService:(NSString *)imageName{
    

}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        NJImageCropperViewController *imgEditorVC = [[NJImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
